import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { NzTypographyModule } from 'ng-zorro-antd/typography';
import { Api } from 'src/app/shared/api/api';
@Component({
  selector: 'app-consent',
  templateUrl: './consent.component.html',
  styleUrl: './consent.component.less',
  changeDetection: ChangeDetectionStrategy.Default,
  imports: [NzIconModule, NzCardModule, NzTypographyModule, NzTableModule, NzToolTipModule]
})
export class ConsentComponent implements OnInit {
  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);

  // 获取授权确认信息响应
  consentResult: NzSafeAny = {};
  // 所有的scope
  scopes: NzSafeAny[] = [];
  // 已授权的scope
  approvedScopes: NzSafeAny[] = [];
  // 提交/拒绝按钮加载状态
  loading = false;

  setOfCheckedScope = new Set<string>();
  checked = false;
  indeterminate = false;

  ngOnInit(): void {
    this.http.get(`${Api.BaseOAuthApi}/consent/parameters${window.location.search}`, null).subscribe({
      next: (res: NzSafeAny) => {
        if (res.data) {
          console.log(res);
          this.consentResult = res.data;
          this.scopes = [...res.data.scopes];
          this.approvedScopes = res.data.previouslyApprovedScopes.map((e: NzSafeAny) => e.scope);
        } else {
          this.msg.warning(res.message);
        }
      },
      error: err => {
        this.msg.warning(`获取客户端与scope信息失败：${err.message || err.statusText}`);
      }
    });
  }

  onItemChecked(scope: string, checked: boolean): void {
    if (checked) {
      this.setOfCheckedScope.add(scope);
    } else {
      this.setOfCheckedScope.delete(scope);
    }
    console.log(this.setOfCheckedScope);
  }

  onAllChecked(checked: boolean): void {
    let temp = new Set<string>();
    if (checked) {
      this.scopes.forEach(element => {
        temp.add(element.scope);
      });
    }
    this.setOfCheckedScope = temp;
    console.log(this.setOfCheckedScope);
  }

  consent(agree: boolean) {
    if (this.setOfCheckedScope && this.setOfCheckedScope.size > 0) {
      const data = new FormData();
      data.append('state', this.consentResult.state);
      data.append('client_id', this.consentResult.clientId);
      data.append('user_code', this.consentResult.userCode);
      if (agree) this.setOfCheckedScope.forEach(e => data.append('scope', e));
      this.http.post(Api.BaseAuthApi + this.consentResult.requestURI, data, null).subscribe(res => {
        console.log(res);
        if (res.data) {
          window.location.href = res.data;
        }
      });
    } else {
      this.msg.warning('请至少选择一项');
    }
  }
}
